"""

"""

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.spinner import Spinner
from kivy.uix.switch import Switch
from kivy.uix.slider import Slider
from src.core.ollama_client import OllamaClient

class AppSettingsPanel(BoxLayout):
    """"""
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = 'vertical'
        self.spacing = 15
        self.padding = 20
        
        # 
        self.title = " Settings"
        
        self.settings = {}
        self._build_ui()
    
    def _build_ui(self):
        """"""
        #  - self.titleKivy
        title_label = Label(
            text=self.title,
            font_size=48,  # 放大两倍字体
            size_hint_y=None,
            height=80,
            bold=True,
            color=(0.2, 0.6, 0.9, 1),
            markup=True
        )
        self.add_widget(title_label)
        
        # 
        settings_grid = GridLayout(
            cols=2,
            spacing=10,
            size_hint_y=None,
            height=400
        )
        
        # Whisper
        settings_grid.add_widget(Label(text="Whisper Model:", halign='left', font_size=32))
        self.whisper_spinner = Spinner(
            text='base',
            values=['tiny', 'base', 'small', 'medium', 'large'],
            size_hint_x=None,
            width=150
        )
        self.whisper_spinner.bind(text=self._on_whisper_change)
        settings_grid.add_widget(self.whisper_spinner)
        
        # Ollama
        settings_grid.add_widget(Label(text="Ollama Model:", halign='left', font_size=32))
        ollama_values, detected = self._get_ollama_options()
        default_ollama = ollama_values[0] if ollama_values else 'qwen2:7b'
        self.ollama_spinner = Spinner(
            text=default_ollama,
            values=ollama_values,
            size_hint_x=None,
            width=150
        )
        self.ollama_spinner.bind(text=self._on_ollama_change)
        settings_grid.add_widget(self.ollama_spinner)

        # 如果未检测到模型，禁用下拉并提示
        if not detected:
            self.ollama_spinner.disabled = True
            self.ollama_spinner.text = '未检测到模型'
            settings_grid.add_widget(Label(text="未检测到 Ollama 模型，请启动 Ollama 并拉取模型", font_size=20))
        
        # 
        settings_grid.add_widget(Label(text="Recognition Language:", halign='left', font_size=32))
        self.language_spinner = Spinner(
            text='auto',
            values=['auto', 'zh', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'ru'],
            size_hint_x=None,
            width=150
        )
        self.language_spinner.bind(text=self._on_language_change)
        settings_grid.add_widget(self.language_spinner)
        
        # 
        settings_grid.add_widget(Label(text="Summary Style:", halign='left', font_size=32))
        self.style_spinner = Spinner(
            text='detailed',
            values=['concise', 'detailed', 'bullet_points', 'academic', 'business'],
            size_hint_x=None,
            width=150
        )
        self.style_spinner.bind(text=self._on_style_change)
        settings_grid.add_widget(self.style_spinner)
        
        # GPU
        settings_grid.add_widget(Label(text="GPU Acceleration:", halign='left', font_size=32))
        self.gpu_switch = Switch(active=True)
        self.gpu_switch.bind(active=self._on_gpu_change)
        settings_grid.add_widget(self.gpu_switch)
        
        # 
        settings_grid.add_widget(Label(text="Auto Cleanup:", halign='left', font_size=32))
        self.cleanup_switch = Switch(active=True)
        self.cleanup_switch.bind(active=self._on_cleanup_change)
        settings_grid.add_widget(self.cleanup_switch)
        
        # 
        settings_grid.add_widget(Label(text="Segment Duration (seconds):", halign='left', font_size=32))
        self.chunk_slider = Slider(
            min=300, max=1800, value=600, step=300,
            size_hint_x=None, width=150
        )
        self.chunk_slider.bind(value=self._on_chunk_change)
        settings_grid.add_widget(self.chunk_slider)
        
        # 
        settings_grid.add_widget(Label(text="Concurrent Workers:", halign='left', font_size=32))
        self.workers_slider = Slider(
            min=1, max=8, value=2, step=1,
            size_hint_x=None, width=150
        )
        self.workers_slider.bind(value=self._on_workers_change)
        settings_grid.add_widget(self.workers_slider)
        
        self.add_widget(settings_grid)
        
        # 
        button_layout = BoxLayout(
            orientation='horizontal',
            size_hint_y=None,
            height=50,
            spacing=10
        )
        
        # 
        reset_btn = Button(text="Reset to Defaults", font_size=32, height=60)
        reset_btn.bind(on_press=self._reset_settings)
        button_layout.add_widget(reset_btn)
        
        # 
        save_btn = Button(text="Save Settings", font_size=32, height=60, background_color=(0.2,0.7,0.3,1), color=(1,1,1,1))
        save_btn.bind(on_press=self._save_settings)
        button_layout.add_widget(save_btn)
        
        self.add_widget(button_layout)
        
        # 
        self._update_settings()

    def _get_ollama_options(self):
        """从本地 Ollama 检测已安装的模型列表，不做预设回退"""
        try:
            from kivy.app import App
            app = App.get_running_app()
            host = app.settings_data.get('ollama_host', 'localhost')
            port = app.settings_data.get('ollama_port', 11434)
            client = OllamaClient(base_url=f"http://{host}:{port}")
            models = client.list_models()
            names = [m.get('name') for m in models if m.get('name')]
            if names:
                return names, True
        except Exception:
            pass
        return [], False
    
    def _on_whisper_change(self, spinner, text):
        """Whisper"""
        self.settings['whisper_model'] = text
    
    def _on_ollama_change(self, spinner, text):
        """Ollama"""
        self.settings['ollama_model'] = text
    
    def _on_language_change(self, spinner, text):
        """"""
        self.settings['language'] = text
    
    def _on_style_change(self, spinner, text):
        """"""
        self.settings['summary_style'] = text
    
    def _on_gpu_change(self, switch, active):
        """GPU"""
        self.settings['use_gpu'] = active
    
    def _on_cleanup_change(self, switch, active):
        """"""
        self.settings['auto_cleanup'] = active
    
    def _on_chunk_change(self, slider, value):
        """"""
        self.settings['chunk_duration'] = int(value)
    
    def _on_workers_change(self, slider, value):
        """"""
        self.settings['max_workers'] = int(value)
    
    def _update_settings(self):
        """"""
        self.settings = {
            'whisper_model': self.whisper_spinner.text,
            'ollama_model': self.ollama_spinner.text,
            'language': self.language_spinner.text,
            'summary_style': self.style_spinner.text,
            'use_gpu': self.gpu_switch.active,
            'auto_cleanup': self.cleanup_switch.active,
            'chunk_duration': int(self.chunk_slider.value),
            'max_workers': int(self.workers_slider.value)
        }
    
    def _reset_settings(self, instance):
        """"""
        self.whisper_spinner.text = 'base'
        self.ollama_spinner.text = 'qwen2:7b'
        self.language_spinner.text = 'auto'
        self.style_spinner.text = 'detailed'
        self.gpu_switch.active = True
        self.cleanup_switch.active = True
        self.chunk_slider.value = 600
        self.workers_slider.value = 2
        self._update_settings()
    
    def _save_settings(self, instance):
        """"""
        self._update_settings()
        # TODO: 
        print("Settings saved:", self.settings)
    
    def get_settings(self):
        """"""
        self._update_settings()
        return self.settings
    
    def set_settings(self, settings):
        """"""
        if 'whisper_model' in settings:
            self.whisper_spinner.text = settings['whisper_model']
        if 'ollama_model' in settings:
            self.ollama_spinner.text = settings['ollama_model']
        if 'language' in settings:
            self.language_spinner.text = settings['language']
        if 'summary_style' in settings:
            self.style_spinner.text = settings['summary_style']
        if 'use_gpu' in settings:
            self.gpu_switch.active = settings['use_gpu']
        if 'auto_cleanup' in settings:
            self.cleanup_switch.active = settings['auto_cleanup']
        if 'chunk_duration' in settings:
            self.chunk_slider.value = settings['chunk_duration']
        if 'max_workers' in settings:
            self.workers_slider.value = settings['max_workers']
        
        self._update_settings()